﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Core.BOL;

namespace ScoutNET.Helpers
{
    public static class SiteMapHelper
    {
        public static MvcHtmlString SiteMapTree(this HtmlHelper html, List<Sitemap> lSitemap)
        {
            StringBuilder sbHtmlOutput = new StringBuilder();

            if (lSitemap.Count() > 0)
            {
                string topic = string.Empty;
                sbHtmlOutput.Append("<dl>");
                for (int i = 0; i < lSitemap.Count; i++)
                {
                    Sitemap sitemap = lSitemap[i];
                    if ((topic == string.Empty || topic != sitemap.Topic) && !string.IsNullOrEmpty(sitemap.Topic))
                    {
                        sbHtmlOutput.Append(@"<div class=""siteMapItem"">");
                        sbHtmlOutput.AppendFormat("<dt>{0}</dt>", sitemap.Topic);
                    }

                    sbHtmlOutput.Append("<dd>");
                    if (sitemap.Url != string.Empty)
                    {
                        sbHtmlOutput.AppendFormat(@"<a href=""{0}"">{1}</a>", sitemap.Url, sitemap.Title);
                    }
                    else
                    {
                        sbHtmlOutput.AppendFormat(@"{1}", sitemap.Url, sitemap.Title);
                    }
                    
                    if (sitemap.Child != null && sitemap.Child.Count > 0)
                    {
                        sbHtmlOutput.Append(html.SiteMapTree(sitemap.Child));
                    }

                    topic = sitemap.Topic;
                    sbHtmlOutput.Append("</dd>");

                    int j = i + 1;
                    if (j < lSitemap.Count)
                    {
                        if (lSitemap[j].Topic != sitemap.Topic && !string.IsNullOrEmpty(sitemap.Topic))
                        {
                            sbHtmlOutput.Append("</div>");
                        }
                    }
                }
                sbHtmlOutput.Append("</dl>");
            }

            return MvcHtmlString.Create(sbHtmlOutput.ToString());
        }
    }
}
